package com.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 咕唧
 * @Date 2022/5/20 20:07
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
@SessionAttributes({"gender", "session1"})
public class UserController {
    @RequestMapping("/add1")
    public String addUser(String username, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("UserController的addUser方法执行了");
        //接受数据放到request中
        request.setAttribute("username", username);
        return "/result.jsp";
    }

    //model域中的数据可以通过request传递
    @RequestMapping("/add2")
    public String addUser2(String username, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("UserController的addUser2方法执行了");
        //接受数据放到request中
        model.addAttribute("name", username);
        //model中的数据在重定向的时候会拼接成参数
        return "redirect:/result.jsp";
    }

    //modelandview 可以集中管理 跳转和数据
    @RequestMapping("/add3")
    public ModelAndView addUser3(String username, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("UserController的addUser3方法执行了");
        //转发
        ModelAndView mv = new ModelAndView();
        // 设置视图名，视图名称就是跳转方式
        mv.setViewName("/result.jsp");
        // 增加数据
        mv.addObject("username", "收到的名字是" + username);
        return mv;
    }

    @RequestMapping("/add4")
    public String addUser4(String username, Model model, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("UserController的addUser4方法执行了");
        //接受数据放到model中
        model.addAttribute("session1", username);
        model.addAttribute("gender", "gender中的数据");
        //model中的数据在重定向的时候会拼接成参数
        return "redirect:/result2.jsp";
    }

    @RequestMapping("/clean")
    public String addUser5(SessionStatus status) {
        System.out.println("UserController的addUser5方法执行了");
        //清理session中的数据
        status.setComplete();
        return "redirect:/result.jsp";
    }
}
